<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class asset_files
{
  
  function load( $file_type, $directories = array(), $base_url = '', $exclude_files = array() )
  {
    $ar_files = array();
    
    if ( is_array($directories) )
    {
    	foreach ( $directories as $directory )
    	{
        $ar_files = array_merge($ar_files,asset_files::_read_dir($directory,$file_type,$base_url,$exclude_files));
    	}
    }
    else
    {
      $ar_files = array_merge($ar_files,asset_files::_read_dir($directories,$file_type,$base_url,$exclude_files));
    }
    
    sort($ar_files);
    
    $ar_return_str = array();
    
    switch (strtolower($file_type))
    {
      case 'css':
        foreach ( $ar_files as $file_url ) $ar_return_str[] = '<link rel="stylesheet" type="text/css" href="'.$file_url.'" />';
        break;
        
      case 'js':
        foreach ( $ar_files as $file_url ) $ar_return_str[] = '<script src="'.$file_url.'" type="text/javascript" ></script>';
        break;
    }
    
    echo implode("\n\t",$ar_return_str)."\n";
  }
  
  function _read_dir($directory = '',$file_type,$base_url='',$exclude_files=array())
  {
    $ar_files = array();
    $asset_dir = ROOTPATH."assets/";
    $folder = !empty($base_url) ? $base_url : $file_type;
    $dir = $asset_dir."$folder/$directory/";
    $dir_url = base_url()."assets/$folder/$directory/";
    
    if ($dh = @opendir($dir))
    {
      while (($file = readdir($dh)) !== false)
      {
        if ($file === '.' || $file === '..' || preg_match("/(?<!.)\..+/i",$file) || in_array($file,$exclude_files))
          continue;

        if (is_file($dir . $file) AND !preg_match("/\.\_.+/i",$file))
          if ( strtolower(pathinfo($dir.$file,PATHINFO_EXTENSION)) == strtolower($file_type) )
            $ar_files[] = $dir_url.$file;
      }
      closedir($dh);
    }
    return $ar_files;
  }

}